package karaokit.com;

import android.media.MediaPlayer;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

/**
 * This method is the Lyrics Synchronizer. This class is a new thread class that 
 * is created when a lyrics is loaded with the song and it is responsible to 
 * synchronize the lyrics lines with the song progress. 
 */
public class LyricsSynconizer extends Thread {
	
	private MediaPlayer mPlayer;
	private TextView mView;
	private Lyrics mLyric;
	private Handler handler;	
	private int syncDiff = 0;
	
	
	public int getSyncDiff() {
		return syncDiff;
	}

	public void setSyncDiff(int syncDiff) {
		this.syncDiff = syncDiff;
	}
	
	/**
	 * Default constructor
	 * @param mp the media player thats running
	 * @param lyrics the lyrics to synchronize
	 * @param view the text view where to show the lyrics at
	 */
	public LyricsSynconizer(MediaPlayer mp, Lyrics lyrics, TextView view) {
		mPlayer = mp;
		mView = view;
		mLyric = lyrics;
		handler = new Handler();
	}

	
	@Override
	public void run() {				
		while (mPlayer.isPlaying()) {
				//If the media plater is playing then we need to update the 
				//lyrics
				handler.post(sync);
				//Then the thread is going to sleep for half a second
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}	
		}		
	}
	
	/**
	 * This is the synchronizing runnable object. It get the current position 
	 * of the media player and get the needed line from the lyrics file. It 
	 * is able to add a synchronization delta to adjust the lyrics as the user 
	 * desire 
	 */
	final Runnable sync = new Runnable() {
        public void run() {
        	Log.e("Runnable updateResults", "Runnable updateResults");
        	mView.setText(mLyric.getLine(mPlayer.getCurrentPosition() + getSyncDiff()));				
        }
   };
   
   @Override
   public void destroy() {	   
	   handler.removeCallbacks(sync);
	   super.destroy();
   }
}
